/*
This demo visualises the railway stations in Tokyo (東京) as a graph.

This demo gives examples of

- loading elements via http request
- loading style via http request
- using the preset layout with predefined positions in each element
- using motion blur for smoother viewport experience
- using `min-zoomed-font-size` to show labels only when needed for better performance
*/

/* global document, fetch, window, cy, cytoscape, Promise, tippy */

document.addEventListener('DOMContentLoaded', function(){

  var $ = function(sel){ return document.querySelector(sel); };

  // hyperscript-like function
  var h = function(tag, attrs, children){
    var el = document.createElement(tag);

    if(attrs != null && typeof attrs === typeof {}){
      Object.keys(attrs).forEach(function(key){
        var val = attrs[key];

        el.setAttribute(key, val);
      });
    } else if(typeof attrs === typeof []){
      children = attrs;
    }

    if(children != null && typeof children === typeof []){
      children.forEach(function(child){
        el.appendChild(child);
      });
    } else if(children != null && typeof children === typeof ''){
      el.appendChild(document.createTextNode(children));
    }

    return el;
  };

  var toJson = function(obj){ return obj.json(); };
  var toText = function(obj){ return obj.text(); };

  // get exported json from cytoscape desktop
  var graphP = fetch('tokyo-railways.json').then(toJson);

  // also get style
  var styleP = fetch('tokyo-railways.cycss').then(toText);

  // when both graph export json and style loaded, init cy
  Promise.all([ graphP, styleP ]).then(initCy);

  function initCy( then ){
    var loading = document.getElementById('loading');
    var expJson = then[0];
    var styleJson = then[1];
    var elements = expJson.elements;

    loading.classList.add('loaded');

    window.cy = cytoscape({
      container: document.getElementById('cy'),
      layout: { name: 'preset' },
      style: styleJson,
      elements: elements,
      motionBlur: true,
      selectionType: 'single',
      boxSelectionEnabled: false
    });

    //mendData();
	
	initCnMap();
    //bindRouters();
	var c1 = cy.collection();
	c1 = c1.union(cy.elements("node[line_name *= '京沪线'],edge[line_name *= '京沪线']"));
	c1 = c1.sort(function(e1, e2){
		return e1.data('index_jh') - e2.data('index_jh');
		
	});
	var i = 0;
	var highlightJh = function(){
		  if( i < c1.length ){
			c1[i].addClass('highlightedJh');
			i++;
			if(c1[i].isNode()){
				setTimeout(highlightJh, 1000);
			}else{
				setTimeout(highlightJh, 10000);
			}
		  }
		};
	highlightJh();
	
	ii = 0;
	var c2 = cy.collection();
	c2 = c2.union(cy.elements("node[line_name *= '京广线'],edge[line_name *= '京广线']"));
	c2 = c2.sort(function(e1, e2){
		return e1.data('index_jg') - e2.data('index_jg');
		
	});
	var highlightJg = function(){
		  if( ii < c2.length ){
			c2[ii].addClass('highlightedJg');
			ii++;
			if(c1[ii].isNode()){
				setTimeout(highlightJg, 1000);
			}else{
				setTimeout(highlightJg, 5000);
			}
		  }
		};
	highlightJg();
	
	iii = 0;
	var c3 = cy.collection();
	c3 = c3.union(cy.elements("node[line_name *= '京张'],edge[line_name *= '京张']"));
	c3 = c3.sort(function(e1, e2){
		return e1.data('index_jz') - e2.data('index_jz');
		
	});
	var highlightJz = function(){
		  if( iii < c3.length ){
			c3[iii].addClass('highlightedJz');
			iii++;
			if(c3[iii].isNode()){
				setTimeout(highlightJz, 1000);
			}else{
				setTimeout(highlightJz, 3000);
			}
		  }
		};
	highlightJz();
  }

  function mendData(){
    // because the source data doesn't connect nodes properly, use the cytoscape api to mend it:

    cy.startBatch();

    // put nodes in bins based on name
    var nodes = cy.nodes();
    var bin = {};
    var metanames = [];
    for( var i = 0; i < nodes.length; i++ ){
      var node = nodes[i];
      var name = node.data('station_name');
      var nbin = bin[ name ] = bin[ name ] || [];

      nbin.push( node );

      if( nbin.length === 2 ){
        metanames.push( name );
      }
    }

    // connect all nodes together with walking edges
    for( var i = 0; i < metanames.length; i++ ){
	  //console.log("in ... ");
      var name = metanames[i];
      var nbin = bin[ name ];

      for( var j = 0; j < nbin.length; j++ ){
        for( var k = j + 1; k < nbin.length; k++ ){
          var nj = nbin[j];
          var nk = nbin[k];
		  
          cy.add({
            group: 'edges',
            data: {
              source: nj.id(),
              target: nk.id()
            }
          });

          //.css({
        //    'line-color': 'yellow'
          // });
        }
      }

    }

    cy.endBatch(); //.autolock( true );
  }
	
	
	
});